package engine.newUi
{
	import com.greensock.TweenLite;
	
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.ResPath;
	import engine.flag.PlayerActionFlag;
	import engine.flag.ResourcesPath;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.tip.TipsMainLogic;
	import engine.ui.AlertUI;
	import engine.ui.lite.BaseUI;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.utils.setTimeout;
	
	import flashx.textLayout.container.ScrollPolicy;
	
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.Scroll.NxScrollPanel;
	import newx.com.control.button.NxButton;
	import newx.com.control.group.NxViewGroup;
	import newx.com.control.table.NxTable;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowDragType;
	import newx.com.control.window.NxWindowEvent;
	import newx.com.loader.SwfLoader;
	
	public class QuestionUI extends BaseUI
	{
		private static var self:QuestionUI;
		private var model:ModelLocator;
		private var rankArr:Vector.<RankVo>;
		private var roleModel:MovieClip;
		private var scale:Number	=	0.4;
		private var bindIndex:int	=	-1;
		private var floorAwardObj:Object;
		public 	 var awardStyle:int	=	1;
		
		public var bg_right:MovieClip;
		public var BackLine1:MovieClip;
		public var BackLine2:MovieClip;
		public var BackLine3:MovieClip;
		public var BackLine4:MovieClip;
		public var startBtn:NxButton;
		public var titleLbl:NxLabel;
		public var title:NxTable;
		public var describeTitle:NxLabel;
		public var describeLbl:NxLabel;
//		public var describeLbl2:NxLabel;
		public var answerAgainLbl:NxLabel;
		public var scrollPanel:NxScrollPanel;
		public var viewGroup_text:NxViewGroup;
		public var answerStepMc:MovieClip;
		public var bgPic:NxClip;
		public var answerCountLbl:NxLabel;
		
		
		public function QuestionUI(popupUI:Boolean=true)
		{
			super(popupUI);
		}
		
		public static function getInstance():QuestionUI
		{
			if(self == null)
			{
				self 		= 	new QuestionUI();
			}
			return self;
		}
		
		override public function Init():void
		{
			model	=	ModelLocator.getInstance();
			model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_QUESTION),freshInfo);
			answerAgainLbl.visible	=	false;
			scrollPanel.addView(viewGroup_text);
			scrollPanel.verticalScrollPolicy	=	ScrollPolicy.AUTO;
			scrollPanel.horizontalScrollPolicy	=	ScrollPolicy.OFF;
			bindIndex	=	BindManage.getInstance().BindProp(ModelLocator.getInstance().scene.Role,"CurAnswerCount",this,"changeItemIndex");
			floorAwardObj	=	StaticIni.getIniObj("FloorAward");
			windowBG.dragSpaceType	=	NxWindowDragType.Window_NONE;
		}
		
		public function set changeItemIndex(val:int):void
		{
			showInfo();
		}
		
		private function freshInfo(e:CustomMsgEvent):void
		{
			var index:int	=	e.pList[0];
			switch(index)
			{
				//刷新排名
				case 3:
					var arrInfo:Array	=	e.pList.slice(1);
					rankArr	=	new Vector.<RankVo>();
					var length:int	=	arrInfo.length;
					for(var i:int=0;i<length;i+=2)
					{
						rankArr.push(new RankVo(arrInfo[i],arrInfo[i+1]));
					}
					freshRank();
					break;
				//一轮结束
				case 4:
					QuestionItemUI.getInstance().submitBtn.label	=	StaticIni.getSwfLangStr("UIString_1000376");
					QuestionItemUI.getInstance().awardBtn.enabled	=	false;
					QuestionItemUI.getInstance().hide();
					showInfo();
					break;
			}
		}
		
		private function freshRank():void
		{
			viewGroup_text.visible	=	true;
			viewGroup_text.row	=	rankArr.length;
			scrollPanel.addView(viewGroup_text);
			scrollPanel.vscroll = 0;
			var mc:MovieClip;
			for( var j:int=	0;j < rankArr.length;j++)
			{
				mc		=	viewGroup_text.getChildAt(j) as MovieClip;
				if(mc == null)return;
				(mc.getChildByName("txt0") as TextField).htmlText= ""+ (j+1);
				(mc.getChildByName("txt1") as TextField).htmlText= ""+ rankArr[j].name;
				(mc.getChildByName("txt2") as TextField).htmlText= ""+ rankArr[j].score;
			}
		}
		
		private function clearRank():void
		{
			viewGroup_text.row	=	rankArr.length;
			var mc:MovieClip;
			for( var j:int=	0;j < rankArr.length;j++)
			{
				mc		=	viewGroup_text.getChildAt(j) as MovieClip;
				if(mc == null)return;
				(mc.getChildByName("txt0") as TextField).htmlText= ""+ (j+1);
				(mc.getChildByName("txt1") as TextField).htmlText= ""+ rankArr[j].name;
				(mc.getChildByName("txt2") as TextField).htmlText= ""+ rankArr[j].score;
			}
		}
		
		public function showMove():void
		{
			var index:int	=	model.scene.Role.GetProperties("CurFloorCount");
			var stepNow:DisplayObject	=	answerStepMc.getChildByName( "mc_"+(index) );//index
			goFromTo( new Point(roleModel.x,roleModel.y) , new Point(stepNow.x,stepNow.y) );
		}
		
		override protected function BeforeShow():void
		{
			addEvents();
			showInfo();
			showMode();
			stopPlay();
			bgPic.source	=	ResPath.SWF + "AnswerBG.swf";
			scrollPanel.vscroll = 0;
		}
		
		override protected function AfterHide():void
		{
			removeEvents();
			startBtn.enabled=startBtn.visible=true;
			answerAgainLbl.visible	=	false;
			QuestionItemUI.getInstance().hide();
			roleModel.stop();
			bgPic.source	=	"";
		}
		
		private function stopPlay():void
		{
			(answerStepMc.getChildByName( "mc_0") as MovieClip).gotoAndStop(1);
			var index:int	=	model.scene.Role.GetProperties("CurFloorCount");
			for(var i:int=1;i<6;i++)
			{
				var mc:MovieClip	=	answerStepMc.getChildByName( "mc_"+ i ) as MovieClip;
				if(i >= index)
				{
					mc.gotoAndStop(2);
					mc.addEventListener(MouseEvent.MOUSE_OVER,onBoxOver);
					mc.addEventListener(MouseEvent.MOUSE_OUT,onBoxOut);
				}else
				{
					mc.removeEventListener(MouseEvent.MOUSE_OVER,onBoxOver);
					mc.removeEventListener(MouseEvent.MOUSE_OUT,onBoxOut);
					mc.gotoAndStop(1);
				}
			}
		}
		
		private function onBoxOver(e:MouseEvent):void
		{
			var name:String	=	e.currentTarget.name;
			var index:int	=	1;
			switch(name)
			{
				case "mc_1":
					index	=	1;
					break;
				case "mc_2":
					index	=	2;
					break;
				case "mc_3":
					index	=	3;
					break;
				case "mc_4":
					index	=	4;
					break;
				case "mc_5":
					index	=	5;
					break;
			}
			var arr:Array		=	(floorAwardObj[ "floor"+ (index) +"_"+1 ] as String).split(",");
			TipsMainLogic.instance.showWideString(StaticIni.getSwfLangStrVar("UIString_1000413",[ arr[1],arr[3] ] ),150);
		}
		
		private function onBoxOut(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();
		}
		
		private function addEvents():void
		{
			startBtn.addEventListener(MouseEvent.CLICK,startQuestion);
			windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClose);
		}
		
		private function removeEvents():void
		{
			startBtn.removeEventListener(MouseEvent.CLICK,startQuestion);
			windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClose);
		}
		
		private function onClose(e:NxWindowEvent):void
		{
			hide();
		}
		
		private function showMode():void
		{
			if(roleModel==null)
			{
				var swfURL:String	=	ResourcesPath.getRoleModel(model.scene.Role);
				SwfLoader.StartLoad(swfURL, null,  function loadOver(mc:MovieClip,pl:Array):void
				{
					if(mc)
					{
						if(mc.numChildren == 1 && mc.totalFrames == 1 )
						{
							mc = mc.getChildAt( 0 ) as MovieClip;
						}else
						{
							mc = ResManager.copy( mc ) as  MovieClip;
						}
						mc.scaleX	=	mc.scaleY	=	scale;
						roleModel	=	mc;
					}
					else
					{
						roleModel			=	ResManager.newResClass("custSkin_86") as MovieClip;
					}
					answerStepMc.addChild(roleModel);
					rolePoistion();
				} );
			}
			else
			{
				rolePoistion();
			}
		}
		
		private function rolePoistion():void
		{
			roleModel.gotoAndPlay(PlayerActionFlag.NormalWait);
			var index:int	=	model.scene.Role.GetProperties("CurFloorCount");
			var stepNow:DisplayObject	=	answerStepMc.getChildByName( "mc_"+(index-1) );//index-1
			goFromTo( new Point(stepNow.x , stepNow.y ) );//资源对应的point坐标
		}
		
		private function goFromTo(startPoint:Point,toPoint:Point=null):void
		{
			roleModel.x	=	startPoint.x;
			roleModel.y	=	startPoint.y;
			if(toPoint!=null)
			{
				roleModel.gotoAndPlay(PlayerActionFlag.Run);
				
				var index:int	=	model.scene.Role.GetProperties("CurFloorCount");
				var stepNow:DisplayObject	=	answerStepMc.getChildByName( "mc_"+(index) );//index+1
				var stepLast:DisplayObject	=	answerStepMc.getChildByName( "mc_"+(index-1) );//index
				(stepLast as MovieClip).gotoAndStop(1);
				(stepNow as MovieClip).gotoAndStop(2);
				
				
				toPoint.x>roleModel.x ? roleModel.scaleX=scale : roleModel.scaleX= -scale;
				
				TweenLite.to(roleModel,3,{x:toPoint.x , y:toPoint.y });
				
				TweenLite.delayedCall(2,function():void
				{
					TweenLite.killTweensOf(roleModel,true);
					(stepNow as MovieClip).gotoAndStop(3);
					TweenLite.to(roleModel,1,{x:toPoint.x , y:toPoint.y , onComplete:function():void
					{
						(stepNow as MovieClip).gotoAndStop(1);
						
						stepNow.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT));
						stepNow.removeEventListener(MouseEvent.MOUSE_OVER,onBoxOver);
						stepNow.removeEventListener(MouseEvent.MOUSE_OUT,onBoxOut);
						
						roleModel.gotoAndPlay(PlayerActionFlag.NormalWait);
						if( QuestionItemUI.getInstance().CurCount == 5)
						{
							startBtn.visible	=	true;
							answerAgainLbl.visible	=	false;
						}
						var arr:Array		=	(floorAwardObj[ "floor"+ (index) +"_"+awardStyle ] as String).split(",");
						var txt:NxLabel	=	new NxLabel();
						txt.htmlText		=	StaticIni.getSwfLangStrVar("UIString_1000377",[ arr[1],arr[3] ]);
						txt.x				=	roleModel.x - txt.width*0.5 + 20;
						txt.y				=	roleModel.y - roleModel.height + 20;
						answerStepMc.addChild(txt);
						TweenLite.to(txt,2,{y:"-50" , alpha: 0 , onComplete:function():void{txt.htmlText="";answerStepMc.removeChild(txt);} });
						setTimeout( function():void{ if(QuestionUI.getInstance().stage) QuestionItemUI.getInstance().showOrHide()}, 2500);
					}
					});
				} );
			}
		}
		
		private function showInfo():void
		{
//			describeLbl.htmlText	=	StaticIni.getSwfLangStr("描述");
			answerCountLbl.htmlText	=	StaticIni.getSwfLangStrVar("UIString_1000381",[model.scene.Role.GetProperties("CurAnswerCount"),5]);//已答xx题
			if(rankArr==null || rankArr.length==0) viewGroup_text.visible	=	false;
//			trace(QuestionItemUI.getInstance().CurCount);
			if( model.scene.Role.GetProperties("CurAnswerCount") < 5 )
			{
				startBtn.label	=	StaticIni.getSwfLangStr("UIString_1000374");//开始答题
			}
			else if( model.scene.Role.GetProperties("CurAnswerCount") == 5 )
			{
				startBtn.enabled	=	false;
				startBtn.label	=	StaticIni.getSwfLangStr("UIString_1000376");//答题已结束
//				startBtn.label	=	StaticIni.getSwfLangStr("再次答题");
			}
			if( model.scene.Role.GetProperties("RefreshQuestionCount") == 1 && model.scene.Role.GetProperties("CurAnswerCount")==5 )
			{
				startBtn.enabled	=	false;
			}
			
			
		}
		
		private function startQuestion(e:MouseEvent):void
		{
			if(  model.scene.Role.GetProperties("CurAnswerCount") == 5 )
			{
				AlertUI.showAlert(StaticIni.getSwfLangStr("提示"),StaticIni.getSwfLangStrVar("",[StaticIni.getIniVar("question_info","answerAgainAward")]),AlertUI.YES|AlertUI.NO,
				function(type:int, str:String, clickData:*):void
				{
					if (type	==	AlertUI.YES)
					{
						showQuestion();
						SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_AFFIRM_CHARGE,16);
					}
				}
				);
				return;
			}
			else
			{
				showQuestion();
			}
			function showQuestion():void
			{
				QuestionItemUI.getInstance().show();
				startBtn.visible	=	false;
				answerAgainLbl.visible	=	true;
			}
		}
		
		
	}
}

class RankVo
{
	public var name	:String   //名字
	public var score	:Number;  //积分
	public function RankVo(name:String,score:Number)
	{
		this.name 		= name;
		this.score		= score;
	}
}